# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : socket_namespace.py
# Time       ：2024/9/11 20:45
# Author     ：Y-aong
# version    ：python 3.10
# Description：socketio 命名空间
"""
from flask_socketio import SocketIO, emit
from flask_socketio.namespace import Namespace

from public.logger import logger
from public.utils.message_manager import NoticeMessageManager, RunningLoggerMessageManager


class NoticeNamespace(Namespace):
    def __init__(self, namespace, socketio: SocketIO):
        super().__init__(namespace)
        self.socketio = socketio

    def on_connect(self):
        logger.info('notice client connected')

    def on_disconnect(self):
        logger.info('notice client disconnected')

    def on_notice(self, message):
        logger.info(f'notice message received, message: {message}')
        emit('notice', {'message': 'ok hello from debug client'}, namespace='/notice')

    def background_thread(self):
        while True:
            self.socketio.sleep(1)
            message = NoticeMessageManager().subscribe()
            self.socketio.emit('notice', message, namespace='/notice')
            print(f'background_thread send message: {message}')


class RunningLoggerNamespace(Namespace):

    def __init__(self, namespace, socketio: SocketIO):
        super().__init__(namespace)
        self.socketio = socketio
        self.message_manager = RunningLoggerMessageManager()

    def on_connect(self):
        logger.info('running logger client connected')

    def on_disconnect(self):
        logger.info('running logger client disconnected')

    def on_running_logger(self, message):
        logger.info(f'running_logger message received, message: {message}')
        if message == 'start':
            self.socketio.start_background_task(self.background_thread)

    def background_thread(self):
        while True:
            running_logger = self.message_manager.subscribe()
            self.socketio.sleep(1)
            if running_logger:
                self.socketio.emit('running_logger', running_logger, namespace='/running_logger')


class DebugNamespace(Namespace):
    def __init__(self, namespace, socketio):
        super().__init__(namespace)
        self.socketio = socketio

    def on_connect(self):
        logger.info('debug client connected')

    def on_disconnect(self):
        logger.info('debug client disconnected')

    def on_debug(self, message):
        logger.info(f'debug message received, message: {message}')
        emit('debug', 'ok hello from debug client')


def register_socketio(app):
    socketio = SocketIO(app, async_mode='gevent', cors_allowed_origins='*')
    socketio.on_namespace(NoticeNamespace('/notice', socketio))
    socketio.on_namespace(RunningLoggerNamespace('/running_logger', socketio))
    socketio.on_namespace(DebugNamespace('/debug', socketio))

    return socketio
